package cn.flying.base.sys.web;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.flying.base.common.constants.Constants;
import cn.flying.base.common.enums.RtCodeEnum;
import cn.flying.base.common.vo.Rt;
import cn.flying.base.sys.configuration.exception.CaptchaException;
import cn.flying.base.sys.configuration.shiro.CaptchaUsernamePasswordToken;
import cn.flying.base.sys.service.SysUserService;


/**
 * Created with IntelliJ IDEA.
 *
 * @description:
 * @author: lvyong
 * @date: 2019-12-04
 * @time: 11:12 上午
 * @version: 1.0
 */
@Controller
public class LoginController {
    private final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Resource
    private SysUserService sysUserService;

    /**
     * 登录页面
     *
     * @return
     */
    @RequestMapping("login")
    public String login() {
        return "login";
    }

    /**
     * 注册页面
     *
     * @return
     */
    @RequestMapping("register")
    public String register() {
        return "register";
    }

    /**
     * 注销登录
     *
     * @return
     */
    @RequestMapping("doLogout")
    @ResponseBody
    public Rt doLogout() {
        SecurityUtils.getSubject().logout();
        return Rt.success("注销成功！");
    }

    /**
     * 登录认证
     *
     * @param request
     * @return
     */
    @RequestMapping("doLogin")
    @ResponseBody
    public Rt doLogin(HttpServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String captcha = request.getParameter("captcha");
        String remember = request.getParameter("remember");
        boolean rememberMe = "on".equals(remember) ? true : false;

        Subject subject = SecurityUtils.getSubject();
        CaptchaUsernamePasswordToken token = new CaptchaUsernamePasswordToken(username, password, rememberMe, captcha);
        try {
            subject.login(token);
            subject.getSession().setAttribute("userInfo", (String) SecurityUtils.getSubject().getPrincipal());
            String access_token = UUID.randomUUID().toString().replaceAll("-", "");
            subject.getSession().setAttribute(Constants.ACCESS_TOKEN, access_token);
            sysUserService.updateUserLoginTimeByUsername(username);
            Map<String, String> map = new HashMap<>();
            map.put(Constants.ACCESS_TOKEN, access_token);
            return Rt.success("登入成功", map);
        } catch (LockedAccountException e) {
            logger.error("登录失败，该用户已被冻结！", e);
            return Rt.result(RtCodeEnum.R10002);
        } catch (AccountException e) {
            logger.error("该用户不存在！", e);
            return Rt.result(RtCodeEnum.R10001);
        } catch (CaptchaException e) {
            logger.error("验证码异常", e);
            return Rt.result(RtCodeEnum.R10004);
        } catch (AuthenticationException e) {
            logger.error("登录失败，用户或者密码错误", e);
            return Rt.result(RtCodeEnum.R10003);
        } catch (Exception e) {
            logger.error("系统异常", e);
            return Rt.error("系统异常！");
        }
    }

    /**
     * 注册用户
     *
     * @return
     */
    @RequestMapping("doRegister")
    @ResponseBody
    public String doRegister() {
        String str = "{\n" +
                "  \"code\": 0\n" +
                "  ,\"msg\": \"注册成功\"\n" +
                "  ,\"data\": {\n" +
                "    \n" +
                "  }\n" +
                "}";
        return str;
    }

    /**
     * 忘记密码
     *
     * @return
     */
    @RequestMapping("forget")
    public String forget() {
        return "forget";
    }





}
